/*
 * frequency_driver.c
 *
 * Created: 2014-01-14 16:40:49
 *  Author: Johan
 */ 

#include <stdint.h>
#include <avr/interrupt.h>
#include "sensor.h"
#include "frequency_driver.h"

int ic_result = -1;

unsigned char clock_sel = 1;


 void set_active_sensor(int sensor_number){
	 if(sensor_number == 0)
	 {
		 EVSYS.CH0MUX = SENSOR_0; 
	 }
	 else if(sensor_number == 1)
	 {
		 EVSYS.CH0MUX = SENSOR_1;
	 }
	 else if(sensor_number == 2){
		 EVSYS.CH0MUX = SENSOR_2;
	 }
	 else if(sensor_number == 3){
		 EVSYS.CH0MUX = SENSOR_3;
	 }
 }
void init_frequency(void){
// Connect Event Channel 0 to the input pin SENSOR_0 to TCCA's clock input pin.

    EVSYS.CH0MUX = SENSOR_0; 

// Set Event Channel 1 to trigger on counter A (TCCA) overflow, causing an Input Capture on counter B
	
	EVSYS.CH1MUX = EVSYS_CHMUX_TCCA_OVF_gc; 

//Select event channel 0 as clock source for TCCB

	TCCB.CTRLA = TC_CLKSEL_EVCH0_gc; 

// Select Event Action 0001 => Input Capture, and Event Source select = 0b1001 => 

	TCCB.CTRLD = (TC1_EVACT_gm & TCB_EVACT0_bm) | (TCB_EVSEL_gm & (TCB_EVSEL3_bm | TCB_EVSEL0_bm));

//Select Event Channel 1 as TCCB Input Capture enable to Capt Channel A

	TCCB.CTRLB = TCB_CCAEN_bm; // Capture enable
} 

void start_frequency_measurement(void){ 
/*	Clear input signal counter (Timer B) */
	TCCB.CNTL =	0;
	TCCB.CNTH =	0;
	ic_result = -1;
	TCCB_INTFLAGS |= TCCB_OVFIF_bm;
	
/*	Clear timer A overflow flag 
 *	This flag is used to signal to the application code that input capture
 *	results are ready.
 *
 */
	TCCA_INTFLAGS |= TCCA_OVFIF_bm;

/*	Load timer A with gate count to overflow value, which is set to 62500*/

	TCCA.CNTL = TCCA_CNT_TO_OVF_L;
	TCCA.CNTH = TCCA_CNT_TO_OVF_H;
	
/*  Set timer A interrupt priority level to High */

	TCCA.INTCTRLA = TC_OVFINTLVL_HI_gc;
	
/* Timer A set clock input */
	TCCA.CTRLA = TC_CLKSEL_DIV8_gc;
	
/*With the clock input set to 2Mhz / 8 and the counting max set to 62500,
 *this gives (1 / (2000000 / 8)) * 62500 = 0.25s until Timer A overflows.
 *So the actual frequency returned has to be divided by 2 (since it counts both positive and negative edges)
 *and then multiplied by 4 since the counting interval is 1/4 second*/
}

int get_frequency_result(void){ 
	
	return	ic_result;
}

void clear_frequency_result(void){

	ic_result = -1;
}

/*!  The following ISR is executed when TCCA overflows.  This will stop the clock to TCCA 
 *  and combine the upper and lower 8 bits of the TCCB capture register into ic_result
 */

ISR(TCCA_OVF_vect){
		/* Stop timer A*/
		TCCA.CTRLA = 0;																				
		if((TCCB_INTFLAGS & 0x01) != 0)	//If timer B overflow flag is set then send max value, so it does not get a "loop" value
		{
			ic_result = 0xffff;
		}
		else
		{
			ic_result= TCCB.CCABUFL + (TCCB.CCABUFH<<8);
		}
}





